<?php
namespace app\user\controller;

use app\common\controller\Front;

class Reset extends Front
{
    private $smsList = [];
    
    public function _initialize()
    {
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        
		parent::_initialize();
        
        if(!$this->smsList=model('user/Captcha','loglic')->smsList()){
            $this->error('error_captcha_disabled');
        }
    }
    
    public function index()
    {
        $this->assign('sms_list', $this->smsList);
        
        return $this->fetch();
    }
    
    //发送验证码（AJAX）
    public function notice()
    {
        $resetName = input('post.reset_name');
        //表单验证
        if(!is_mobile($resetName)){
            if(!is_email($resetName)){
                $this->error(lang('error_user_empty'));
            }
        }
        //图形验证码
        if(captcha_check(input('post.img_captcha')) == false){
            $this->error(lang('error_captcha'));
        }
        //发送频率限制
        if(!model('user/Captcha','loglic')->interval()){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //发送验证码
        if(!model('user/Captcha','loglic')->reset($resetName)){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //返回结果
        $this->success(lang('success'), 'user/login/index', ['action'=>'notice']);
    }
    
    //根据验证码重设密码
    public function update()
    {
        $post = input('post.');
        //验证规则
        $validate = new \think\Validate([
            'reset_name'    => 'require',
            'reset_captcha' => 'require',
            'reset_pwd'     => 'length:6,30',
            //'__token__'     => 'require|token',
        ],[
            'reset_name.require'    => lang('error_name_require'),
            'reset_pwd.length'      => lang('error_length'),
            'reset_captcha.require' => lang('error_captcha_require'),
        ]);
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }
        //验证码验证
        if(!model('user/Captcha','loglic')->check($post['reset_name'],$post['reset_captcha'],'reset')){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //修改密码
        $result = db('user')->update([
            'user_id'   => model('user/Captcha','loglic')->getUserId(),
            'user_pass' => md5(trim($post['reset_pwd'])),
        ]);
        if(!$result){
            $this->error(db('user')->getError());
        }
        //操作成功
        $this->success(lang('success'), 'user/login/index', ['action'=>'update']);
    }
}